import React from 'react';
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import {useNavigation} from '@react-navigation/native';

interface NavigationBarProps {
  height?: number;
  title?: string;
  isSave?: boolean;
  showBackBtn?: boolean;
  showRightBtn?: boolean;
  titleRight?: () => React.ReactElement;
  handleUpdate?(): void;
}

const NavigationBar: React.FC<NavigationBarProps> = props => {
  const {
    height = 50,
    title = '-',
    isSave = false,
    showBackBtn = false,
    showRightBtn = false,
    titleRight,
    handleUpdate,
  } = props;
  const insets = useSafeAreaInsets();
  const navigation = useNavigation();

  const handleBack = () => {
    navigation.goBack();
  };

  const root = StyleSheet.create({
    wrap: {
      height,
      marginTop: insets.top,
      marginLeft: insets.left,
      marginRight: insets.right,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
    },
  });

  return (
    <View style={root.wrap}>
      {showBackBtn && (
        <TouchableOpacity onPress={handleBack}>
          <MaterialIcons
            style={styles.iconWrap}
            name="arrow-back-ios-new"
            size={18}
          />
        </TouchableOpacity>
      )}
      <View style={styles.titleWrap}>
        <Text style={styles.title}>{title}</Text>
        {!!titleRight && <View>{titleRight()}</View>}
      </View>
      {showRightBtn && (
        <View style={styles.rightWrap}>
          {isSave ? (
            <TouchableOpacity onPress={handleUpdate}>
              <MaterialIcons style={{color: '#ff7600'}} name="star" size={22} />
            </TouchableOpacity>
          ) : (
            <TouchableOpacity onPress={handleUpdate}>
              <MaterialIcons
                style={styles.iconWrap}
                name="star-border"
                size={22}
              />
            </TouchableOpacity>
          )}
          <TouchableOpacity>
            <MaterialIcons style={styles.iconWrap} name="share" size={20} />
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

export default NavigationBar;

const styles = StyleSheet.create({
  iconWrap: {
    color: '#999',
  },
  titleWrap: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    gap: 8,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  rightWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
});
